/*
 * Project: BooEditor
 * Author:  Johannes Kuhaupt
 * Last Change:
 *    by:   $Author: $
 *    date: $Date:   $
 * Copyright (c): Johannes Kuhaupt
 * Licence: Creative Commons CC BY-NC-SA 3.0
 */
package control.boo;

import control.GuiManager;
import control.SettingsManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Johannes Kuhaupt
 */
public class LejosUploader extends AbstractJavaTask {

    File path;

    /**
     *
     * @param pFile
     */
    public LejosUploader(String pFile) {
        this.taskFile = new File(pFile);
    }

    /**
     *
     */
    @Override
    public void run() {
        this.guiMan.setUploaderReady(false);
        this.startLejosTask();
    }

    private String stripExtension(String str) {
        // Handle null case specially.

        if (str == null) {
            return null;
        }

        // Get position of last '.'.

        int pos = str.lastIndexOf(".");

        // If there wasn't any '.' just return the string as is.

        if (pos == -1) {
            return str;
        }

        // Otherwise return the string, up to the dot.

        return str.substring(0, pos);
    }

    private void startLejosTaskWithoutExtension() {
        String pathToBoo = SettingsManager.getStringSettingValue("PATH_TO_LEJOSUPLOADER");

        File classFile = new File(taskFile.getParent() + File.separator + this.stripExtension(this.taskFile.getName()) + ".class");
        System.err.println(classFile.toString());

        File booExe = new File(pathToBoo);
        if (booExe.exists() && booExe.canExecute() && (booExe.getName().equals("nxj.bat") || booExe.getName().equals("nxj")) && classFile.exists() && classFile.canRead()) {
            pb = new ProcessBuilder(pathToBoo, this.stripExtension(this.taskFile.getName()));
            pb.redirectErrorStream(true);
            pb.directory(path);

            try {
                currentProcess = pb.start();
                processStarted = true;
            } catch (IOException ex) {
                this.guiMan.setOutputInFrame(this.compilerResult);
                this.guiMan.setUploaderReady(true);
                this.guiMan.showErrorMessage(GuiManager.getLangBundle().getString("MsgErrorInterpreting"));
                Logger.getLogger(LejosUploader.class.getName()).log(Level.SEVERE, null, ex);
                System.err.println("Error, startBooTask failed (Interpreter): " + ex.toString());
            }

        }


    }

    private void startLejosTaskWithExtension() {
        String pathToBoo = SettingsManager.getStringSettingValue("PATH_TO_LEJOSUPLOADER");
        String pathToJar = SettingsManager.getStringSettingValue("PATH_TO_JAREXTENSION");
        File booExe = new File(pathToBoo);
        File jarFile = new File(pathToJar);
        File classFile = new File(taskFile.getParent() + File.separator + this.stripExtension(this.taskFile.getName()) + ".class");
        File nxjFile = new File(taskFile.getParent() + File.separator + this.stripExtension(this.taskFile.getName()) + ".nxj");
        String justName = this.stripExtension(this.taskFile.getName());



        if (booExe.exists() && booExe.canExecute() && (booExe.getName().equals("nxj.bat") || booExe.getName().equals("nxj")) && classFile.exists() && classFile.canRead() && jarFile.exists() && jarFile.canRead() && jarFile.isFile()) {
            pb = new ProcessBuilder(pathToBoo, "-cp", pathToJar + File.pathSeparatorChar + path.getAbsolutePath(), "-o", nxjFile.getAbsolutePath(), justName);
            pb.redirectErrorStream(true);
            pb.directory(path);


            try {
                currentProcess = pb.start();
                processStarted = true;
            } catch (IOException ex) {
                this.guiMan.setOutputInFrame(this.compilerResult);
                this.guiMan.setUploaderReady(true);
                this.guiMan.showErrorMessage(GuiManager.getLangBundle().getString("MsgErrorInterpreting"));
                Logger.getLogger(LejosUploader.class.getName()).log(Level.SEVERE, null, ex);
                System.err.println("Error, startBooTask failed (Interpreter): " + ex.toString());
            }


        }

    }

    private void startLejosTask() {
        compilerResult = "";
        currentProcess = null;
        processStarted = false;

        path = new File(taskFile.getParent());

        String pathToJar = SettingsManager.getStringSettingValue("PATH_TO_JAREXTENSION");

        if (pathToJar.isEmpty()) {
            this.startLejosTaskWithoutExtension();
        } else {
            this.startLejosTaskWithExtension();
        }

        if (processStarted) {
            this.readOutputStream();
            
            if(this.compilerResult.contains("Upload successful")){
                    this.guiMan.setOutputInFrame(GuiManager.getLangBundle().getString("MsgUploadSuccess"));
                    this.guiMan.setStatusInfo(GuiManager.getLangBundle().getString("StatusMsgUploadSuccess"));
                }
                else{
                    this.guiMan.setOutputInFrame(this.compilerResult);
                    this.guiMan.setStatusInfo(GuiManager.getLangBundle().getString("StatusMsgUploadError"));
                    this.guiMan.showOutputTab();
                }
                this.guiMan.setCompilerReady(true);
            
            this.guiMan.setUploaderReady(true);
        } else {
            this.guiMan.showErrorMessage(GuiManager.getLangBundle().getString("MsgErrorBooi"));
            this.guiMan.setUploaderReady(true);
        }



    }
}
